# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals

import json
import os
import shutil
import uuid

from PIL import ImageFile
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, \
	HttpResponseNotAllowed
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import DetailView

from Persimmon import settings
from auser.forms import UserFormLogIn, ChangepwdForm, ChangeEmailForm
from .tasks import send_email
from auser.models import User


def user_register(request):
	return render(request, 'auser/register.html')


@csrf_exempt
def registerVerify(request):
	if request.method == 'POST':
		username = request.POST.get('username')
		email = request.POST.get('email')
		password = request.POST.get('password')
		filterResult = User.objects.filter(username=username)
		if len(filterResult) > 0:
			return HttpResponse('-1')
		filterResult = filterResult.filter(email=email)
		if len(filterResult) > 0:
			return HttpResponse('-1')
		ua = User.objects.create_user(username, email=email, password=password, is_active=False)  # 创建用户
		ua.save()
		token = ua.generate_confirm_token(ua.id)
		# REW:celery 异步邮件
		try:
			send_email.delay(email, template='auser/email/confirm', user=ua, token=token)
		except:
			send_email(email, template='auser/email/confirm', user=ua, token=token)
		return HttpResponse('1')
	else:
		return HttpResponse('0')


def user_login(request):
	print(request.method)
	if request.method == 'POST':
		uf = UserFormLogIn(request.POST)
		if uf.is_valid():
			# 获取表单信息
			username = uf.cleaned_data['username']
			password = uf.cleaned_data['password']
			#  验证
			user = authenticate(username=username, password=password)
			if user is not None and user.is_active:  # 用户不空
				# session框架保存用户ID
				login(request, user)
				print(request.session.items())
				return HttpResponseRedirect(reverse('movie:movie_index', args=(1,)))
			else:
				return HttpResponseRedirect(reverse('auser:login'), {'error': '用户不存在'})
	# return render_to_response('movie/login.html', {'error': '用户不存在'})
	# return HttpResponse("该用户不存在")
	else:
		return render(request, 'auser/login.html', {'next': next})


# 退出
@login_required
def user_logout(request):
	logout(request)
	return HttpResponseRedirect("/auser/login/")


class Homepage(DetailView):
	template_name = "auser/homepage.html"
	model = User
	context_object_name = 'this_user'

	def get_context_data(self, **kwargs):
		context = super(Homepage, self).get_context_data(**kwargs)
		print(self.request.session.items())
		return context


@login_required(login_url='auser:login', )
def user_info_amend(request, pk=1):
	to_user = get_object_or_404(User, pk=pk)
	if request.user != to_user:
		return HttpResponseNotAllowed
	if request.method == 'POST':
		uphone = request.POST.get('tel', None)
		uname = request.POST.get('nick-name', None)
		about_me = request.POST.get('about-me', None)
		id = to_user.id
		if uphone:
			to_user.telephone = uphone
		if uname:
			to_user.nick_name = uname
		if about_me:
			to_user.about_me = about_me
		to_user.save()
		request.session['user_info'] = uname
		return HttpResponseRedirect(reverse('auser:homepage', kwargs={"pk": id}))
	return render(request, 'auser/user_amend.html', {"this_user": to_user})


# todo:后台验证
def confirm(request, id, token):
	print(id)
	try:
		cur_user = User.objects.get(pk=id)
	except:
		return False
	if cur_user.is_active:
		return HttpResponseRedirect(reverse('movie:movie_index', args=(1,)))
	if cur_user.confirm(token):
		print(cur_user.username)
		return HttpResponseRedirect(reverse('auser:login'))
	else:
		print('hello')
		return HttpResponseRedirect(reverse('movie:movie_index', args=(1,)))


@login_required
def changepwd(request, pk):
	if request.method == 'GET':
		form = ChangepwdForm()
		return render(request, 'auser/changepwd.html', {'form': form})
	else:
		form = ChangepwdForm(request.POST)
		if form.is_valid():
			username = request.user.username
			oldpassword = request.POST.get('oldpassword', '')
			user = authenticate(username=username, password=oldpassword)
			if user is not None and user.is_active:
				newpassword = request.POST.get('newpassword1', '')
				user.set_password(newpassword)
				user.save()
				return render(request, 'auser/login.html', {'relogin': True})
			else:
				return render(request, 'auser/changepwd.html', {'form': form})
		else:
			return render(request, 'auser/changepwd.html', {'form': form})


def amend_avatar(request, pk):
	return render(request, 'auser/amend_avatar.html')

# REW:
@login_required
def change_avatar(request, pk):
	ctx = dict()
	to_user = User.objects.get(pk=pk)
	uuid = ''
	marginTop = 0
	marginLeft = 0
	width = 0
	height = 0

	if request.method == "POST":
		file = request.FILES.get("Filedata", None)
		(upload_flag, savepath) = _upload(file)
		if upload_flag:
			ctx["message"] = u"上传成功！"
			ctx["upload_flag"] = 1
		else:
			ctx["message"] = u"上传出错！"
			ctx["upload_flag"] = 0
		ctx["savepath"] = savepath
		ctx["this_user"] = to_user
		return render(request, 'auser/amend_avatar.html', ctx)
	print('get start')
	if request.GET.get('marginTop'):
		marginTop = int(request.GET.get('marginTop'))
	if request.GET.get('marginLeft'):
		marginLeft = int(request.GET.get('marginLeft'))
	if request.GET.get('width'):
		width = int(request.GET.get('width'))
	if request.GET.get('height'):
		height = int(request.GET.get('height'))
	if request.GET.get('uuid'):
		uuid = request.GET.get('uuid')
		print('===uuid:' + request.GET.get('uuid'))
		request.session['replace_site_icon_uuid'] = uuid  # 保存UUID
	if request.GET.get('replace_flag'):
		print('why not')
		filepath = request.GET.get('savepath')
		olduuid = request.session.get('replace_site_icon_uuid', filepath)

		path = os.path.join(settings.MEDIA_ROOT, settings.SOURCE_IMAGE_TMP)
		if filepath and olduuid:
			if os.path.isfile(os.path.join(path, filepath)):
				# 先把新文件，换成旧文件名字
				try:
					newname = os.path.join(settings.MEDIA_ROOT, 'upload/avatar', olduuid)
					newname = newname.replace("\\", "/")
					# os.rename(os.path.join(path, filepath), newname)
					# 覆盖
					oldpath = os.path.join(settings.MEDIA_ROOT, settings.SOURCE_IMAGE_TMP, olduuid).replace("\\", "/")
					shutil.move(oldpath, newname)
					# 裁切
					try:
						from PIL import Image
						path = os.path.join(settings.MEDIA_ROOT, 'upload/avatar', olduuid).replace("\\", '/')
						f = Image.open(path)
						xsize, ysize = f.size
						# box变量是一个四元组(左，上，右，下)。
						box = (marginLeft, marginTop, marginLeft + width, marginTop + height)
						print(box)
						f.crop(box).save(path)
						path = os.path.join('upload/avatar',olduuid)
						request.user.avatar = path
						request.user.save()

					# return HttpResponseRedirect(reverse('auser:homepage',args=(request.user.id)))
					except Exception as e:
						print(e.message)
					return HttpResponse(json.dumps({'message': '替换成功,关闭窗口'}))
				except Exception as e:
					print(e)
			else:
				print('error.==')
	return render(request, 'auser/amend_avatar.html',{"this_user": to_user})


def _upload(file):
	'''
	图片上传函数
	'''
	if file:
		path = os.path.join(settings.MEDIA_ROOT, settings.SOURCE_IMAGE_TMP)
		if not os.path.exists(path):  # 如果目录不存在创建目录
			os.makedirs(path)

		file_name = str(uuid.uuid1()) + ".jpg"
		path_file = os.path.join(path, file_name)
		parser = ImageFile.Parser()
		for chunk in file.chunks():
			parser.feed(chunk)
		img = parser.close()
		try:
			if img.mode != "RGB":
				img = img.convert("RGB")
			img.save(path_file, 'jpeg', quality=100)
			print('img.save:' + path_file)
		except Exception as e:
			print(e)
			return (False, "")

		return (True, file_name)

	return (False, "")


@csrf_exempt
def uploadify_script(request):
	response = HttpResponse()
	response['Content-Type'] = "text/javascript"  # 响应报文
	ret = "0"
	file = request.FILES.get("Filedata", None)
	if file:
		if _upload(file):
			ret = "1"
		ret = "2"
	response.write(ret)
	return response


@login_required
def changeEmail(request, pk):
	if request.method == "POST":
		form = ChangeEmailForm(request.POST)
		if form.is_valid():
			email = form.cleaned_data['email']
			new_email = form.cleaned_data['email_new']
			ua = get_object_or_404(User, pk=pk)
			if ua and ua.email == email:
				ua.email = new_email
				ua.save()
				send_email.delay(email, send_type="reset_email", template='auser/email/reset', user=ua)
				return redirect('movie:movie_index', page=1)
			# return HttpResponseRedirect(reverse('movie:movie_index', args=(1,)))
			else:
				return render(request, 'auser/changeemail.html', {'form': form,
				                                                  'error': "email不对"})
		else:
			return render(request, 'auser/changeemail.html', {'form': form})
	else:
		form = ChangeEmailForm()
		return render(request, 'auser/changeemail.html', {'form': form})
